<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height:60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="hAdd"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table :data="list" border="">
              <el-table-column label="序号" width="50" type="index" />
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <!-- 作用于插槽 #default -->
                <template #default="{row}">
                  <el-button size="small" type="success" @click="hAssign(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="hEdit(row)">编辑</el-button>
                  <el-button size="small" type="danger" @click="hDel(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <el-row type="flex" justify="center" align="middle" style="height: 60px">
              <!-- 分页组件 -->
              <el-pagination
                :current-page="pageParams.page"
                :page-sizes="[2, 3, 5, 10,20]"
                :page-size="pageParams.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <!-- 新增或修改弹层 -->
      <el-dialog
        title="新增或修改弹层 "
        :visible.sync="showDialog"
        @closed="resetForm"
      >
        <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="100px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small">取消</el-button>
            <el-button size="small" type="primary" @click="hSubmit">确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>
      <!--  分配权限的弹层 -->
      <el-dialog title="分配权限" :visible.sync="PermissioDalid">
        <AssignPermission v-if="PermissioDalid" :cur-id="curId" @success="PermissioDalid = false" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getRole, addRole, putRole, deleteRole } from '@/api/settings'
import AssignPermission from './assignPermission.vue'
export default {
  name: 'VueHrSettings',

  components: {
    AssignPermission
  },

  data() {
    return {
      showDialog: false,
      PermissioDalid: false, // 分配权限的弹层的显示和隐藏
      list: [],
      // 收集表单收集的数据
      roleForm: {
        name: '',
        description: ''
      },
      // 校验规则
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      pageParams: {
        page: 1, // 页码值
        pagesize: 2 // 每页显示几条数据
      },
      total: 0, // 总共有几条数据
      isEdit: false, // false新增 || true编辑
      curId: ''

    }
  },

  created() {
    this.lodeRole()
  },

  methods: {
    hAssign(id) {
      this.PermissioDalid = true
      this.curId = id
    },
    resetForm() {
      // 重置校验规则
      this.$refs.roleForm.resetFields()
      // 清空表单数据
      this.roleForm = {
        name: '',
        description: ''
      }
    },
    // 兜底校验
    hSubmit() {
      this.$refs.roleForm.validate((valid) => {
        if (!valid) return // 校验失败
        // 校验成功,发送请求
        this.isEdit ? this.doEdit() : this.doAdd()
      })
    },
    hAdd() {
      this.showDialog = true
      // 新增就将 isEdit设为false
      this.isEdit = false
    },
    hEdit(row) {
      // console.log(row, 'row')
      // { ...row }浅拷贝,解决数据表格中数据对象,和表单对象指向同一个地址的问题
      this.roleForm = { ...row }
      this.showDialog = true
      // 编辑就将 isEdit设为true
      this.isEdit = true
    },

    //  编辑
    async doEdit() {
      try {
        const res = await putRole(this.roleForm)
        // console.log(res, '新增')
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        // 新增成功后,重新获取数据渲染列表
        this.lodeRole()
        // 关闭弹层
        this.showDialog = false
      } catch (error) {
        // console.log(error)
        this.$message.error(error)
      }
    },

    // 新增
    async  doAdd() {
      try {
        const res = await addRole(this.roleForm)
        // console.log(res, '新增')
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        // 计算出最大的页码值
        // 新增成功时跳转到新增数据的页码值
        this.total++
        const maxPage = Math.ceil(this.total / this.pageParams.pagesize)
        // 赋值给 this.pageParams.page
        this.pageParams.page = maxPage
        // 新增成功后,重新获取数据渲染列表
        this.lodeRole()
        // 关闭弹层
        this.showDialog = false
      } catch (error) {
        // console.log(error)
        this.$message.error(error)
      }
    },

    // 删除
    async  hDel(id) {
      this.$confirm('您确定要删除吗？, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await deleteRole(id)
        if (res.code === 10000) {
          this.$message.success(res.message)
          // 判断页面数据是否等于一条
          if (this.list.length === 1) {
            this.pageParams.page--
          }
          if (this.pageParams.page <= 0) {
            this.pageParams.page = 1
          }
          this.lodeRole()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    // 当每页条数改变时， 就会触发该函数，val就是改变的条数
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.pageParams.pagesize = val
      this.pageParams.page = 1
      this.lodeRole()
    },
    // 当页码值改变时就会触发该函数，val就是改变的页码值
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.pageParams.page = val
      this.lodeRole()
    },
    // 获取角色列表
    async lodeRole() {
      try {
        const res = await getRole(this.pageParams)
        // console.log(res, '获取角色列表')
        this.list = res.data.rows
        this.total = res.data.total
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
